package com.example.myproject.client;


import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PopupPanel;

/*************************************************************************
 * Class: ModulePanel
 * Purpose: Creates a Module's panel
 * 
 * **********************************************************************/
public class ModulePanel extends DockPanel{
	
	//CREATE VARIABLES
	
	//create a selection panel
	SelectionPanel selection;
	//create a list of modules
	Modules modList;
	//create a Label for current module
	Label currentMod;
	//create a storage variable
	Storage modStore;
	
	//create a listBox object 
	ListBox list;
	
	/*************************************************************************
	 * creates a module panel to select and display information about modules
	 * it will also allow you to import GPS data.
	 * 
	 * **********************************************************************/
	ModulePanel(Modules moduleList)
	{
		//init class vars
		modStore = null;		
		modList = moduleList;
	    selection = new SelectionPanel(moduleList);		
		list = new ListBox();
		//set lists properties
		list.setVisibleItemCount(6);
		list.setSize("200px", "200px");
		//populate list with all modules
		modList.popList(list);	
		
		//set components
		this.setSize("160px","200px");
		
		// add a label to indicate currently selected module
		currentMod = new Label("No Module Selected");
		
		//add a button to select a module
		Button selectMod = new Button("Select Module");		
		selectMod.addClickHandler(new ClickHandler() {
	        public void onClick(ClickEvent event) {
	        	//on click, create a popup of what you can select
	        	popup();				
	        }
	    });
		
		//add a new button for getting GPS coordinates
		Button popButton = new Button("Real-Time Coordinates");
		popButton.addClickHandler(new ClickHandler() {
	        public void onClick(ClickEvent event) {
	        	popUpGetModule();
	        }
	    });
	    
	    //add everything to module panel
		this.setHorizontalAlignment(DockPanel.ALIGN_CENTER);
		this.setVerticalAlignment(DockPanel.ALIGN_MIDDLE);
		this.setStyleName("borderStyle");
		this.add(selectMod, DockPanel.SOUTH);
		this.add(currentMod, DockPanel.SOUTH);
		this.add(popButton, DockPanel.SOUTH);
	
	}
	
	/*************************************************************************
	 * Function: popup
	 * @param: none
	 * Purpose: create a popup panel that contains a list of modules
	 * Return: none
	 * 
	 * **********************************************************************/
	void popup()
	{
		
		//create a PopupPanel
		final PopupPanel pop = new PopupPanel();
		//create a DockPanel
		DockPanel popupContents = new DockPanel();		    
		
		//create a cancel button used to close the popup with no selection
		Button cancelButton = new Button("Cancel");
		cancelButton.addClickHandler(new ClickHandler() {
	        public void onClick(ClickEvent event) {
	        	pop.hide();				
	        }
	    });
		
		//create an ok button used to close the popup
		//set the current module to the selected module on the list
		Button okButton = new Button("OK");
		okButton.addClickHandler(new ClickHandler() {
	        public void onClick(ClickEvent event) {
	        	pop.hide();	
	        	modList.setSelectedModule(list.getSelectedIndex());	        	
	        	currentMod.setText("Selected Module:\n" + String.valueOf(modList.getSelectedModule().getModNum()));	 
	        	//tell slection panel to enable some buttons
	        	selection.notifySelected();
	        }
	    });		
		
		//add the list and the 2 buttons to the popup panel
		popupContents.add(list, DockPanel.NORTH);
		popupContents.add(cancelButton, DockPanel.WEST);
		popupContents.add(okButton, DockPanel.WEST);
		
		//add the DockPanel to the popup
		pop.add(popupContents);
		
		//set the popup panels position and set it to show
		pop.setPopupPosition(302, 201);
		pop.show();
	}
	
	void getHTMLData()
	{
		modList.reset();
		//loop through dictionary and pass all underlying dictionaries into module list to set them
    	int i = 0;
		Dictionary t1= Dictionary.getDictionary("module"+String.valueOf(i+1));        		
		while(t1 != null)
		{
			modList.setModule(i, t1);        			
			i++;
            try
            {
            	t1= Dictionary.getDictionary("module"+String.valueOf(i+1));
            }
            catch(Exception e)
            {
            	//this happens when dictionary list is done
            	t1 = null;
            }
            
            selection.checkMin();
		}	        

		Voices.playSuccessfulCoordinateInput(); 
		//once done create a new popup panel to inform user
		final PopupPanel pop = new PopupPanel();        		
		Button okButton = new Button("Import Complete");
		okButton.addClickHandler(new ClickHandler() {			
	        public void onClick(ClickEvent event) {
	        	pop.hide();	
	        }
	    });		        		
		pop.add(okButton);        		
		pop.setPopupPosition(332, 231);
		pop.show();
	}
	
	void getGPSData()
	{				
		final PopupPanel pop = new PopupPanel();
    	DockPanel contents = new DockPanel();
    	contents.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE);
    	contents.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
    	
    	final ListBox list = new ListBox();
    	list.addItem("Test Case 1");
    	list.addItem("Test Case 2");
    	list.addItem("Test Case 3");
    	list.addItem("Test Case 4");
    	list.addItem("Test Case 5");
    	list.addItem("Test Case 6");
    	list.addItem("Test Case 7");
    	list.addItem("Test Case 8");
    	
    	DockPanel butPanel = new DockPanel();
    	butPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE);
    	butPanel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
    	
    	Button cancelButton = new Button("Cancel");
    	cancelButton.addClickHandler(new ClickHandler() {			
	        public void onClick(ClickEvent event) {
	        	pop.hide();	
	        }
	    });		
    	
    	Button okButton = new Button("Ok");
    	okButton.addClickHandler(new ClickHandler() {	   		
	        public void onClick(ClickEvent event) {
	        	modList.reset();
	        	
	        	String url = "http://www.d.umn.edu/~abrooks/FiveTests.php?q=" + String.valueOf(list.getSelectedIndex()+1);
	        	url = URL.encode(url);
	        	RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
	        	
	        	try {
	        		builder.sendRequest(null, new RequestCallback() {
	        			public void onError(Request request, Throwable exception) { 
	        				Window.alert("onError: Couldn't retrieve JSON");
	        			}
	        			
	        			public void onResponseReceived(Request request, Response response) {
	        				if (200 == response.getStatusCode()) {
	        					String rt = response.getText();	
	        					JSONArray jA =	(JSONArray)JSONParser.parseLenient(rt);
	        		        	for (int i = 0; i < jA.size(); i++) {
	        		        		modList.setModule(i, (JSONObject)jA.get(i));
	        		        	}
	        		        	selection.checkMin();
	        		        	Voices.playSuccessfulCoordinateInput(); 
	        				}
	        				else{
	        					Window.alert("Couldn't retrieve JSON (" + response.getStatusText()+ ")");
	        					}
	        			}
	        		});
	        		
	                
	        	}
	        	catch (RequestException e) {
	        		 Window.alert("RequestException: Couldn't retrieve JSON");
	        	}           	
	        	
	        	pop.hide();	
	        }
	    });		

    	butPanel.add(cancelButton, DockPanel.WEST);
    	butPanel.add(okButton, DockPanel.WEST);
    	
    	contents.add(list, DockPanel.NORTH);
    	contents.add(butPanel, DockPanel.NORTH);
    	pop.add(contents);
    	pop.setPopupPosition(300, 200);
    	pop.show();
	}
	
	void popUpGetModule()
	{
    	final PopupPanel pop = new PopupPanel();
    	DockPanel contents = new DockPanel();
    	contents.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE);
    	contents.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
    	
    	Button htmlBut = new Button("Get Data From Local");
    	htmlBut.addClickHandler(new ClickHandler() {			
	        public void onClick(ClickEvent event) {
	        	pop.hide();	
	        	getHTMLData();
	        }
	    });	
    	
    	Button jsonBut = new Button("Get Data From GPS");
    	jsonBut.addClickHandler(new ClickHandler() {			
	        public void onClick(ClickEvent event) {
	        	pop.hide();	
	        	getGPSData();
	        }
	    });	
    	
    	Button cancelButton = new Button("Cancel Import");
    	cancelButton.addClickHandler(new ClickHandler() {			
	        public void onClick(ClickEvent event) {
	        	pop.hide();	
	        }
	    });		
		
    	contents.add(htmlBut, DockPanel.NORTH);
    	contents.add(jsonBut, DockPanel.NORTH);
    	contents.add(cancelButton, DockPanel.NORTH);
    	pop.add(contents);
    	pop.setPopupPosition(300, 200);
    	pop.show();
	}
	
	/*************************************************************************
	 * get the selection panel
	 * 
	 * **********************************************************************/
	SelectionPanel getSelection()
	{
		return selection;
	}
}
